package com.mzpai.web.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.mzpai.product.model.StoreBrand;
import com.mzpai.product.model.StoreCategory;
import com.mzpai.product.model.StoreProductAttrResultSupplier;
import com.mzpai.product.model.StoreProductAttrSupplier;
import com.mzpai.product.model.StoreProductAttrValueSupplier;
import com.mzpai.product.model.StoreProductCateSupplier;
import com.mzpai.product.model.StoreProductDetailsSupplier;
import com.mzpai.product.model.StoreProductSupplier;
import com.mzpai.product.service.StoreBrandService;
import com.mzpai.product.service.StoreCategoryService;
import com.mzpai.product.service.StoreProductAttrResultSupplierService;
import com.mzpai.product.service.StoreProductAttrSupplierService;
import com.mzpai.product.service.StoreProductAttrValueSupplierService;
import com.mzpai.product.service.StoreProductCateSupplierService;
import com.mzpai.product.service.StoreProductDetailsSupplierService;
import com.mzpai.product.service.StoreProductSupplierService;
import com.mzpai.product.vo.AttrResultSupplierVo;
import com.mzpai.product.vo.AttrValueVo;
import com.mzpai.product.vo.AttrVo;
import com.mzpai.product.vo.StoreProductAttrSingleResultDetailVo;
import com.mzpai.util.BeanUtils;
import com.mzpai.util.DateUtil;
import com.mzpai.util.SplitBatch;
import com.mzpai.util.StringUtils;
import com.mzpai.vo.ResponseVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 上线初始化接口
 * @author ASUS
 */

@Api(value = "上线后初始化工具接口")
@RestController
@RequestMapping("/online")
public class OnlineInitController extends BaseController{
	
 protected Logger logger = LoggerFactory.getLogger(OnlineInitController.class);

 @Autowired
 private StoreBrandService storeBrandService;
 
 @Autowired
 private StoreCategoryService storeCategoryService;
 
 @Autowired
 private StoreProductSupplierService storeProductSupplierService;
 
 @Autowired
 private StoreProductCateSupplierService storeProductCateSupplierService;
 
 @Autowired
 private StoreProductAttrSupplierService storeProductAttrSupplierService;
 
 @Autowired
 private StoreProductAttrValueSupplierService storeProductAttrValueSupplierService;
 @Autowired
 private StoreProductAttrResultSupplierService storeProductAttrResultSupplierService;
 
 @Autowired
 private StoreProductDetailsSupplierService storeProductDetailsSupplierService;
 
 
 /*@ApiOperation(value = "初始化品牌brandCode")
 @RequestMapping(value = "/brandCodeInit", method = RequestMethod.GET)
 public ResponseVo<String> brandCodeInit() throws Exception{
	 
	 
	 Map<String, Object> map=new HashMap<String,Object>();
     map.put("storeId", 0);
     List<StoreBrand> list=storeBrandService.getList(map);
	 for(int i=0;i<list.size();i++){
		 StoreBrand storeBrand=list.get(i);
		 String brandName=storeBrand.getBrandName();
		 String brandCode=storeBrand.getBrandCode();
		 
		 String shouzimstr=ChineseCharacterUtil.convertHanzi2Pinyin(brandName,false).toUpperCase();
	     String firstLetter=shouzimstr.substring(0,1);
	     if(StringUtils.isBlank(brandCode)){
	    	 String brandCodestr=StringUtils.getRandomCode(6);
	    	 storeBrand.setBrandCode(brandCodestr);
	    	 storeBrand.setStoreId(-1);
	     }
	     storeBrand.setFirstLetter(firstLetter);
	     storeBrandService.update(storeBrand);
	 }   
    String result="OK";
	ResponseVo<String> resVo=new ResponseVo<String>();
	resVo.setResult(result);
 	return resVo;
 }*/
 
 
 //数据库手动新增分类是store设置为-1 然后执行此方法
 /*@ApiOperation(value = "初始化商品分类数据")
 @RequestMapping(value = "/categoryInit", method = RequestMethod.GET)
 public ResponseVo<String> categoryInit(@RequestParam(value = "storeId", required = true) Integer storeId) throws Exception{
    String result="OK";
	ResponseVo<String> resVo=new ResponseVo<String>();
	Map<String, Object> map=new HashMap<String,Object>();
	map.put("storeId", storeId);
	List<StoreCategory> list=storeCategoryService.getList(map);
	String catecodefirst="N_";
	for(int i=0;i<list.size();i++){
		StoreCategory storeCategory=list.get(i);
		String cateCodestr=storeCategory.getCateCode();
		if(StringUtils.isBlank(cateCodestr)){
			String cate_Code=StringUtils.getRandomCode(8);
			StoreCategory update=new StoreCategory();
			update.setId(storeCategory.getId());
			update.setCateCode(catecodefirst+cate_Code);
			storeCategoryService.update(update);
		}
	}
	System.out.println(list.size());
	resVo.setResult(result);
 	return resVo;
 }*/
 
 
 
 @ApiOperation(value = "生产初始化品牌数据")
 @RequestMapping(value = "/brandInit", method = RequestMethod.GET)
 public ResponseVo<String> brandInit() throws Exception{
	 
	 Map<String, Object> map=new HashMap<String,Object>();
	 map.put("storeId", -2);
	 List<StoreBrand> list=storeBrandService.getList(map);
	 for(int i=0;i<list.size();i++){
		 StoreBrand storeBrand=list.get(i);
		 String brandName=storeBrand.getBrandName();
		 String brandCode=storeBrand.getBrandCode();
		 logger.info("当前更新品牌个数 "+i+" brandCode="+brandCode);
		 Map<String, Object> querymap0=new HashMap<String,Object>();
		 querymap0.put("brandName", brandName);
		 querymap0.put("storeId", 0);
		 List<StoreBrand> list2=storeBrandService.getList(querymap0);
		 
		 //相同的品牌名称已存在则更新brandcode
		 if(list2!=null && !list2.isEmpty()){
			 StoreBrand querystoreBrand= list2.get(0);
			 StoreBrand updatebrand=new StoreBrand();
			 updatebrand.setBrandId(querystoreBrand.getBrandId());
			 updatebrand.setBrandCode(brandCode);
			 updatebrand.setStoreId(-3);
			 storeBrandService.deleteByBrandCode(brandCode);
	    	 storeBrandService.update(updatebrand);
		 }
		 
		 if(list2==null || list2.isEmpty()){
			 StoreBrand saveStoreBrand=new StoreBrand();
			 BeanUtils.copyProperties(storeBrand, saveStoreBrand);
			 saveStoreBrand.setBrandId(null);
			 saveStoreBrand.setStoreId(-1);
			 storeBrandService.deleteByBrandCode(storeBrand.getBrandCode());
			 storeBrandService.save(saveStoreBrand);
		 }
	 }   
    String result="OK";
	ResponseVo<String> resVo=new ResponseVo<String>();
	resVo.setResult(result);
 	return resVo;
 }
 
 
 
 /*@ApiOperation(value = "商品produce初始化")
 @RequestMapping(value = "/productCodeInit", method = RequestMethod.GET)
 public ResponseVo<String> productCodeInit(@RequestParam(value = "factoryId", required = true) Integer factoryId) throws Exception{
    String result="OK";
	ResponseVo<String> resVo=new ResponseVo<String>();
	Map<String, Object> map=new HashMap<String,Object>();
	map.put("factoryId", factoryId);
	List<StoreProductSupplier> list=storeProductSupplierService.getList(map);
	for(int i=0;i<list.size();i++){
		StoreProductSupplier productSupplier=list.get(i);
		String productbrandCode=productSupplier.getBrandCode();
		Integer brandId=productSupplier.getBrandId();
		StoreBrand storeBrand=storeBrandService.queryByPrimaryId(brandId);
		String brandCode=storeBrand.getBrandCode();
		//如果商品product为空则更新
		if(storeBrand!=null){
			Integer id=productSupplier.getId();
			StoreProductSupplier updateProduct=new StoreProductSupplier();
			updateProduct.setId(id);
			if(!productbrandCode.equals(brandCode)){
				updateProduct.setBrandCode(brandCode);
				updateProduct.setFactoryId(-3);
				storeProductSupplierService.update(updateProduct);;
			}
			
		}else{
			System.out.println("根据品牌id查询结果为空 productid="+productSupplier.getId()+" 品牌id= "+brandId);
		}
	}
	resVo.setResult(result);
 	return resVo;
 }*/
 
 
 
 @ApiOperation(value = "将商品中数据根据code匹配品牌和分类id生产更新旧的商品初始化")
 @RequestMapping(value = "/productInit", method = RequestMethod.GET)
 public ResponseVo<String> productInit(@RequestParam(value = "factoryId", required = true) Integer factoryId) throws Exception{
    String result="OK";
	ResponseVo<String> resVo=new ResponseVo<String>();
	Map<String, Object> map=new HashMap<String,Object>();
	map.put("factoryId", factoryId);
	List<StoreProductSupplier> list=storeProductSupplierService.getList(map);
	for(int i=0;i<list.size();i++){
		StoreProductSupplier productSupplier=list.get(i);
		logger.info("当前更新条数:"+i+"当前商品code "+productSupplier.getProductCode());
		String productCodeStr=productSupplier.getProductCode();
		String brandCode=productSupplier.getBrandCode();
		String cateCode=productSupplier.getCateCode();
		
		StoreBrand storeBrand=storeBrandService.queryByBrandCode(brandCode);
		StoreCategory storeCategory=storeCategoryService.queryByCateCode(cateCode);
		
		//如果商品product为空则更新
		if(storeBrand!=null && storeCategory!=null){
			Integer id=productSupplier.getId();
			StoreProductSupplier updateProduct=new StoreProductSupplier();
			updateProduct.setId(id);
			Integer brandId=storeBrand.getBrandId();
			Integer cateId=storeCategory.getId();
			if(StringUtils.isBlank(productCodeStr)){
				Date d = new Date();
	    		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	    		String dateNowStr = sdf.format(d);
				String shuijicode=StringUtils.getRandomCode(6);
				updateProduct.setProductCode("SP_"+dateNowStr+"_"+shuijicode);
			}else{
				updateProduct.setProductCode(productCodeStr);
			}
			updateProduct.setBrandId(brandId);
			updateProduct.setCateId(String.valueOf(cateId));
			storeProductSupplierService.update(updateProduct);;
		}
	}
	resVo.setResult(result);
 	return resVo;
 }
 
 
 @ApiOperation(value = "根据商品生成各个子表")
 @RequestMapping(value = "/productDetailTable", method = RequestMethod.GET)
 public ResponseVo<String> productDetailTable(@RequestParam(value = "factoryId", required = true) Integer factoryId) throws Exception{
    String result="OK";
	ResponseVo<String> resVo=new ResponseVo<String>();
	Map<String, Object> map=new HashMap<String,Object>();
	map.put("factoryId", factoryId);
	List<StoreProductSupplier> list=storeProductSupplierService.getList(map);
	for(int i=0;i<list.size();i++){
		StoreProductSupplier productSupplier=list.get(i);
		logger.info("当前更新条数:"+i+"当前商品code "+productSupplier.getProductCode());
		String productCode=productSupplier.getProductCode();
		Integer addTime=(int) (new Date().getTime()/1000);
		Integer productId=productSupplier.getId();
		String cateId=productSupplier.getCateId();
		String image=productSupplier.getImage();
		String sliderImage=productSupplier.getSliderImage();
		String detailImg=productSupplier.getDetailImg();
		
		if(!StringUtils.isNullOrBlank(image)){
			image=image.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "");
		}
		
		if(!StringUtils.isNullOrBlank(sliderImage)){
			sliderImage=sliderImage.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "");
		}
        if(!StringUtils.isNullOrBlank(detailImg)){
        	detailImg=detailImg.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "");
		}

		List<String> listdetail=new ArrayList<String>();
		
		if(!StringUtils.isNullOrBlank(detailImg)){
			String arrayDetail[]=detailImg.split(",");
			for(int j=0;j<arrayDetail.length;j++){
				String name=arrayDetail[j].replaceAll("\"", "");;
				listdetail.add(name.trim());
			}
		}
		if(listdetail!=null && !listdetail.isEmpty()){
			//1.设置商品详情 eb_store_product_details_supplier
			List<List<String>> listcoutfenzu=SplitBatch.split(listdetail, 4);
			for(int k=0;k<listcoutfenzu.size();k++){
				List<String> onelist=listcoutfenzu.get(k);
				StringBuffer sb=new StringBuffer();
				for(String ss:onelist){
					sb.append(ss);
					sb.append(",");
				}
				StoreProductDetailsSupplier storeProductDetailsSupplier=new StoreProductDetailsSupplier();
				storeProductDetailsSupplier.setProductId(productId);
				storeProductDetailsSupplier.setProductCode(productCode);
				storeProductDetailsSupplier.setDescription("");
				storeProductDetailsSupplier.setImgs(sb.toString().substring(0, sb.lastIndexOf(",")));
				storeProductDetailsSupplierService.save(storeProductDetailsSupplier);
			}
		}
		//2.设置
		//设置商品辅助分类表 eb_store_product_cate_supplier
	    StoreProductCateSupplier productCateSupplier=new StoreProductCateSupplier();
	    productCateSupplier.setProductId(productId);
	    productCateSupplier.setAddTime(addTime);
	    productCateSupplier.setCateId(Integer.valueOf(cateId));
	    storeProductCateSupplierService.save(productCateSupplier);
	    //3.设置 商品属性表(eb_store_product_attr)
	    StoreProductAttrSupplier attrSupplier=new StoreProductAttrSupplier();
	    attrSupplier.setAttrName("规格");
	    attrSupplier.setAttrValues("默认");
	    attrSupplier.setProductId(productId);
	    attrSupplier.setType(0);
	    storeProductAttrSupplierService.save(attrSupplier);
		//4.设置 商品属性值表
	    StoreProductAttrValueSupplier attrValueSupplier=new StoreProductAttrValueSupplier();
	    attrValueSupplier.setProductId(productId);
	    attrValueSupplier.setSuk("默认");
	    attrValueSupplier.setStock(0);
	    attrValueSupplier.setSales(0);
	    attrValueSupplier.setPrice(productSupplier.getPrice());
    	attrValueSupplier.setMinPrice(productSupplier.getPrice());
    	attrValueSupplier.setCost(productSupplier.getCost());
    	attrValueSupplier.setOtPrice(productSupplier.getOtPrice());
	    attrValueSupplier.setImage(image);
	    //13未时间戳 没有读取到图片条形码前面加N标记
	    attrValueSupplier.setBarCode("000000"+DateUtil.getDateFormateDate()+getNumber(6));
	    
	    String unique=StringUtils.randomString(8,false);
	    attrValueSupplier.setUnique(unique.toLowerCase());
	    attrValueSupplier.setWeight(BigDecimal.valueOf(Double.valueOf(0)));
	    attrValueSupplier.setVolume(BigDecimal.valueOf(Double.valueOf(0)));
	    attrValueSupplier.setBrokerageTwo(BigDecimal.valueOf(Double.valueOf(0)));
	    attrValueSupplier.setBrokerage(BigDecimal.valueOf(Double.valueOf(0)));
	    attrValueSupplier.setType(0);
	    attrValueSupplier.setQuota(0);
	    attrValueSupplier.setQuotaShow(0);
	    attrValueSupplier.setStoreId(0);
	    storeProductAttrValueSupplierService.save(attrValueSupplier);
	    //5.商品属性详情表(eb_store_product_attr_result)
	    String guigeunicode = testgetUnicode("规格");
	    String morenunicode = testgetUnicode("默认");
	    StoreProductAttrResultSupplier attrResultSupplier=new StoreProductAttrResultSupplier();
	    attrResultSupplier.setProductId(productId);
	    attrResultSupplier.setType(0);
	    AttrResultSupplierVo resultVo=new AttrResultSupplierVo();
	    AttrVo attrVo=new AttrVo();
	    attrVo.setValue(guigeunicode);
	    attrVo.setDetailValue("");
	    attrVo.setAttrHidden("");
	    List <String> detail=new ArrayList<String>();
	    detail.add(morenunicode);
	    
	    
	    attrVo.setDetail(detail);
	    List<AttrVo> listAttrVo=new ArrayList<AttrVo>();
	    listAttrVo.add(attrVo);
	    resultVo.setAttr(listAttrVo);
	    
	    AttrValueVo attrValueVo=new AttrValueVo();
	    attrValueVo.setPic(attrValueSupplier.getImage());
	    attrValueVo.setMin_price(String.valueOf(attrValueSupplier.getMinPrice()));
	    attrValueVo.setOt_price(String.valueOf(attrValueSupplier.getOtPrice()));
	    attrValueVo.setStock(0);
	    attrValueVo.setBar_code(attrValueSupplier.getBarCode());
	    attrValueVo.setVolume(String.valueOf(attrValueSupplier.getVolume()));
	    attrValueVo.setWeight(String.valueOf(attrValueSupplier.getWeight()));
	    attrValueVo.setBrokerage("0.00");
	    attrValueVo.setBrokerage_two("0.00");
	    attrValueVo.setCost(String.valueOf(attrValueSupplier.getMinPrice()));
	    attrValueVo.setPrice(String.valueOf(attrValueSupplier.getPrice()));
	    attrValueVo.setValue1(guigeunicode);
	    
	    StoreProductAttrSingleResultDetailVo vo=new StoreProductAttrSingleResultDetailVo();
	    vo.set规格(morenunicode);
	    attrValueVo.setDetail(vo);
	    
	    List<AttrValueVo> listAttrValueVo=new ArrayList<AttrValueVo>();
	    listAttrValueVo.add(attrValueVo);
	    
	    resultVo.setValue(listAttrValueVo);
	    
	    String resultjs=JSON.toJSONString(resultVo);
	    resultjs=resultjs.replaceAll("规格", testgetUnicode("规格"));
	    resultjs=resultjs.replaceAll("/", "\\\\");
	    attrResultSupplier.setResult(resultjs);
	    attrResultSupplier.setChangeTime(addTime);
	    storeProductAttrResultSupplierService.save(attrResultSupplier);
	    
	}
	resVo.setResult(result);
 	return resVo;
 }
 
 
 //随机数工具方法
 public static long getNumber(int length) {
     StringBuilder buf = new StringBuilder();
     Random random = new Random();
/*开头不为0,建议数据量较少时只放开部分，比如1至3开头的数，等业务达到一定数量时，再逐步放开剩余的号码段，由于是固定位数，总数量一定，生成的数越多，重复的几率越大**/
     int firstNumber = random.nextInt(9) + 1; 
     buf.append(firstNumber);

     for(int i = 0; i < length - 1; ++i) {
         buf.append(random.nextInt(10));
     }

     return Long.valueOf(buf.toString());
 }
 
 
 /*@ApiOperation(value = "初始化商品数据")
 @RequestMapping(value = "/productSupplierInit", method = RequestMethod.GET)
 public ResponseVo<String> productSupplierInit(@RequestParam(value = "path", required = true) String path) throws Exception{
	    
	    int count=0;
	    try {
            // 创建CSV读对象
            CsvReader csvReader = new CsvReader(path, ',', Charset.forName("gbk"));
            // 读表头
            csvReader.readHeaders();
            String leftImg="D:\\pythontest\\imgs\\cat\\maomimeirong\\xizaoyongpin\\left\\";
            String centerImg="D:\\pythontest\\imgs\\cat\\maomimeirong\\xizaoyongpin\\center\\";
            
            String fullPath=null;
            
            //设置商品所属分类 2363
    	    String cateId="2429";
    	    String cateCode="N_TLMIU9YU";
    	    Integer factoryId=-1;
    	    
            while (csvReader.readRecord()) {
            	count++;
            	String tiaoxingma=null;
                // 读一整行
//                System.out.println(csvReader.getRawRecord());
                // 读这行的某一列
                String spbh = csvReader.get("spbh").trim();//商品编号
                String pinpai = csvReader.get("pinpai").trim();//品牌
                String name = csvReader.get("name").trim();//商品名称
                String spjg = csvReader.get("spjg").trim();//商品价格
                String cszdj = csvReader.get("cszdj").trim();//厂商指导价
                String spguige = csvReader.get("spguige").trim();//商品规格
                String spleixing = csvReader.get("spleixing").trim();//商品类型
                String lingshileixing = csvReader.get("lingshileixing").trim();//零食类型
                String zhuyaoyuanliao = csvReader.get("zhuyaoyuanliao").trim();//主要原料
                String yingyangchenfen = csvReader.get("yingyangchenfen").trim();//营养成分
                String shiyongduixiang = csvReader.get("shiyongduixiang").trim();//适用对象
                String tedian = csvReader.get("tedian").trim();//用途特点
                
                String shiyingzhengzhuang = csvReader.get("shiyingzhengzhuang").trim();//适应症状
                String yongfayongliang = csvReader.get("yongfayongliang").trim();//用法用量
                String kelidaxiao = csvReader.get("kelidaxiao").trim();//颗粒大小
                String kouweipeifang = csvReader.get("kouweipeifang").trim();//口味配方
                String baozhiqi = csvReader.get("baozhiqi").trim();//出厂保质期
                String chandi = csvReader.get("chandi").trim();//产地
                
                String weight = csvReader.get("weight").trim();//重量
                String huaxianjia = csvReader.get("huaxianjia").trim();//划线价
                String url = csvReader.get("url").trim();//详细链接
//                String str=ChineseCharacterUtil.convertHanzi2Pinyin(pinpai,false).toUpperCase();
//                String first=str.substring(0,1);
                List<String> leftList=FileReadHandler.redaLeftImg(leftImg,spbh);
                List<String> centerList=FileReadHandler.redaLeftImg(centerImg,spbh);
        		Collections.sort(leftList);
        		Collections.sort(centerList);
                
                //左侧图读取条形码
                for(String leftstr:leftList){
                	fullPath=leftImg+leftstr;
                	tiaoxingma=FileReadHandler.decodeBarcode(fullPath);
        			if(!StringUtils.isNullOrBlank(tiaoxingma)&&  tiaoxingma.length()==13&& tiaoxingma.matches("[0-9]+")){
        				break;
        			}else{
        				tiaoxingma=null;
        			}
        		}
                if(StringUtils.isNullOrBlank(tiaoxingma)){
                	//中心图读取条码
                    for(String centerstr:centerList){
                    	fullPath=centerImg+centerstr;
                    	tiaoxingma=FileReadHandler.decodeBarcode(fullPath);
                    	//并且纯数字
                    	if(!StringUtils.isNullOrBlank(tiaoxingma) && tiaoxingma.length()==13 &&  tiaoxingma.matches("[0-9]+")){
            				break;
            			}else{
            				tiaoxingma=null;
            			}
            		}
                }
                if(!StringUtils.isNullOrBlank(tiaoxingma)){
    				System.out.println("商品编号: "+spbh+ "图片路径: "+fullPath+"条形码: "+tiaoxingma);
    			}
                
                //查询品牌获取品牌id
        	    Map<String, Object> brandmap=new HashMap<String,Object>();
        	    brandmap.put("brandName", pinpai.trim());
        	    brandmap.put("storeId", 0);
        	    List<StoreBrand> list=storeBrandService.getList(brandmap);
                if(list==null || list.isEmpty() || list.size()>1){
        	    	throw new Exception("品牌查询数据库为空,brandName="+pinpai+"商品编号  "+spbh);
        	    }
        	    
        	    StoreBrand storeBrand=list.get(0);
        	    Integer brandId=storeBrand.getBrandId();
        	    String brandCode=storeBrand.getBrandCode();
        	    
        	    
        	    Date d = new Date();
        		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        		String dateNowStr = sdf.format(d);
        		
        		String randomstr=StringUtils.randomString(8,true);
        		//年月日时分秒+8位随机数
                String productSupplibarCode=dateNowStr+randomstr;
        	    
        	
        	    Short sort=0;
        	    Integer addTime=(int) (new Date().getTime()/1000);
        	    
        	    if(leftList==null || leftList.isEmpty()){
                	System.err.println("没有获取到左侧图片商品编号: "+spbh+" 波奇地址:"+url);
                }
        	    
                List<String> leftDbList=new ArrayList<String>();
                for(String leftName:leftList){
                	leftDbList.add(leftImg+leftName);
                }
               
                if(centerList==null || centerList.isEmpty()){
                	System.err.println("没有获取到中心图片商品编号: "+spbh+" 波奇地址:"+url);
                }
                
                List<String> centerDbList=new ArrayList<String>();
                for(String centerName:centerList){
                	centerDbList.add(centerImg+centerName);
                }
                
                String image="";
                if(leftDbList!=null && !leftDbList.isEmpty()){
                	image=leftDbList.get(0);
                }
                
                
                String productCode=StringUtils.getRandomCode(15);
                //设置主商品
        	    StoreProductSupplier storeProductSupplier=new StoreProductSupplier();
        	    storeProductSupplier.setBrandId(brandId);
        	    storeProductSupplier.setBrandCode(brandCode);
        	    storeProductSupplier.setCateId(cateId);
        	    storeProductSupplier.setCateCode(cateCode);
        	    storeProductSupplier.setFactoryId(factoryId);
        	    storeProductSupplier.setMerId(0);
        	    storeProductSupplier.setStoreName(name);
        	    storeProductSupplier.setStoreInfo("");
        	    storeProductSupplier.setKeyword(name);
        	    storeProductSupplier.setBarCode(productSupplibarCode);
        	    storeProductSupplier.setPlaceOrigin(chandi);
        	    
        	    
        	    if(!StringUtils.isNullOrBlank(spjg)){
        	    	storeProductSupplier.setPrice(BigDecimal.valueOf(Double.valueOf(spjg)));
        	    }else{
        	    	storeProductSupplier.setPrice(BigDecimal.valueOf(Double.valueOf(0)));
        	    }
        	    
        	    if(!StringUtils.isNullOrBlank(spjg)){
        	    	storeProductSupplier.setVipPrice(BigDecimal.valueOf(Double.valueOf(spjg)));
        	    }else{
        	    	storeProductSupplier.setVipPrice(BigDecimal.valueOf(Double.valueOf(0)));
        	    }
        	    
        	    if(!StringUtils.isNullOrBlank(huaxianjia)){
        	    	storeProductSupplier.setOtPrice(BigDecimal.valueOf(Double.valueOf(huaxianjia)));
        	    }else{
        	    	storeProductSupplier.setOtPrice(BigDecimal.valueOf(Double.valueOf(0)));
        	    }
        	    
        	    storeProductSupplier.setPostage(BigDecimal.valueOf(Double.valueOf(0)));
        	    storeProductSupplier.setIsPostage(0);
        	    storeProductSupplier.setUnitName("");
        	    storeProductSupplier.setSort(sort);
        	    storeProductSupplier.setSales(0);
        	    storeProductSupplier.setStock(0);
        	    storeProductSupplier.setIsShow(1);
        	    storeProductSupplier.setIsHot(0);
        	    storeProductSupplier.setIsBenefit(0);
        	    storeProductSupplier.setIsBest(0);
        	    storeProductSupplier.setIsNew(0);
        	    storeProductSupplier.setAddTime(addTime);
        	    storeProductSupplier.setIsDel(0);
        	    storeProductSupplier.setMerUse(0);
        	    storeProductSupplier.setGiveIntegral(BigDecimal.valueOf(Double.valueOf(0)));
        	    storeProductSupplier.setCost(BigDecimal.valueOf(Double.valueOf(0)));
        	    storeProductSupplier.setIsSeckill(0);
        	    storeProductSupplier.setIsBargain(0);
        	    storeProductSupplier.setIsGood(0);
        	    storeProductSupplier.setIsSub(0);
        	    storeProductSupplier.setFicti(0);
        	    storeProductSupplier.setBrowse(0);
        	    storeProductSupplier.setCodePath("");
        	    storeProductSupplier.setSoureLink("");
        	    storeProductSupplier.setVideoLink("");
        	    storeProductSupplier.setTempId(0);
        	    storeProductSupplier.setSpecType(0);
        	    storeProductSupplier.setActivity("1,2,3");
        	    storeProductSupplier.setSliderImage(leftDbList.toString());
        	    storeProductSupplier.setDetailImg(centerDbList.toString());
        	    storeProductSupplier.setImage(image);
        	    storeProductSupplier.setProductCode(productCode);
        	    storeProductSupplier.setThreeNum(spbh);
        	    storeProductSupplier.setThreeUrl(url);
        	    
        	    if(!StringUtils.isNullOrBlank(zhuyaoyuanliao)){
        	    	storeProductSupplier.setMainMaterial(zhuyaoyuanliao);
       	    }
				if(!StringUtils.isNullOrBlank(yingyangchenfen)){
					storeProductSupplier.setNutritionalComponent(yingyangchenfen);  	
				}
				if(!StringUtils.isNullOrBlank(shiyongduixiang)){
					storeProductSupplier.setApplicableObjects(shiyongduixiang);
				}
				
				if(!StringUtils.isNullOrBlank(kelidaxiao)){
					storeProductSupplier.setParticleSize(kelidaxiao);
				}
				if(!StringUtils.isNullOrBlank(kouweipeifang)){
					storeProductSupplier.setTasteFormula(kouweipeifang);
				}
				if(!StringUtils.isNullOrBlank(baozhiqi)){
					storeProductSupplier.setExpirationDate(baozhiqi);
				}
				
				if(!StringUtils.isNullOrBlank(lingshileixing)){
					storeProductSupplier.setSnacksType(lingshileixing);
				}
				
				if(!StringUtils.isNullOrBlank(shiyingzhengzhuang)){
					storeProductSupplier.setIndications(shiyingzhengzhuang);
				}
				if(!StringUtils.isNullOrBlank(yongfayongliang)){
					storeProductSupplier.setUsageDosage(yongfayongliang);
				}
				if(!StringUtils.isNullOrBlank(tedian)){
					storeProductSupplier.setUseCharacteristics(tedian);
				}
				
				if(!StringUtils.isNullOrBlank(spleixing)){
					storeProductSupplier.setProductType(spleixing);
				}
				
				
        	    //设置商品详情
        	    storeProductSupplierService.save(storeProductSupplier);
        	    StoreProductSupplier queryProduct=storeProductSupplierService.queryByProductCode(productCode);
        	    
//        	    StoreProductSupplier queryProduct=storeProductSupplierService.queryByProductCode("8LOGQ5GG2AZO493");
        	    
        	    Integer productId=queryProduct.getId();
        	    
        	    //设置商品详情
        	    StoreProductDescriptionSupplier productDesc=new StoreProductDescriptionSupplier();
        	    productDesc.setProductId(productId);
        	    productDesc.setDescription(centerDbList.toString());
        	    productDesc.setType(0);
        	    
        	    Map<String, Object> productidmap=new HashMap<String,Object>();
        	    productidmap.put("productId", productId);
        	    
        	    List<StoreProductDescriptionSupplier> listdescsupp=storeProductDescriptionSupplierService.getList(productidmap);
        	   
        	    if(listdescsupp==null || listdescsupp.isEmpty()){
        	    	storeProductDescriptionSupplierService.save(productDesc);
        	    }
        	    
        	    
        	    //设置商品辅助分类表
        	    StoreProductCateSupplier productCateSupplier=new StoreProductCateSupplier();
        	    productCateSupplier.setProductId(productId);
        	    productCateSupplier.setAddTime(addTime);
        	    productCateSupplier.setCateId(Integer.valueOf(cateId));
        	    
        	    List<StoreProductCateSupplier> listproductCate=storeProductCateSupplierService.getList(productidmap);
        	    if(listproductCate==null || listproductCate.isEmpty()){
        	    	 storeProductCateSupplierService.save(productCateSupplier);
        	    }
        	   
        	    
        	    //商品属性表
        	    StoreProductAttrSupplier attrSupplier=new StoreProductAttrSupplier();
        	    attrSupplier.setAttrName("规格");
        	    attrSupplier.setAttrValues("默认");
        	    attrSupplier.setProductId(productId);
        	    attrSupplier.setType(0);
        	    
        	    List<StoreProductAttrSupplier> listattrSupplier=storeProductAttrSupplierService.getList(productidmap);
        	    if(listattrSupplier==null || listattrSupplier.isEmpty()){
        	    	 storeProductAttrSupplierService.save(attrSupplier);
        	    }
        	    
        	    //设置 商品属性值表
        	    StoreProductAttrValueSupplier attrValueSupplier=new StoreProductAttrValueSupplier();
        	    attrValueSupplier.setProductId(productId);
        	    attrValueSupplier.setSuk("默认");
        	    attrValueSupplier.setStock(0);
        	    attrValueSupplier.setSales(0);
        	    
				DecimalFormat    df   = new DecimalFormat("######0.00");   
				String spjgstr=df.format(Double.valueOf(spjg));
				
				String huaxianjiastr=df.format(Double.valueOf(huaxianjia));
				
        	    if(!StringUtils.isNullOrBlank(spjg)){
        	    	attrValueSupplier.setPrice(BigDecimal.valueOf(Double.valueOf(spjgstr)));
        	    	attrValueSupplier.setMinPrice(BigDecimal.valueOf(Double.valueOf(spjgstr)));
        	    	attrValueSupplier.setCost(BigDecimal.valueOf(Double.valueOf(spjgstr)));
        	    }else{
        	    	attrValueSupplier.setPrice(BigDecimal.valueOf(Double.valueOf(0.00)));
        	    	attrValueSupplier.setMinPrice(BigDecimal.valueOf(Double.valueOf(0.00)));
        	    	attrValueSupplier.setCost(BigDecimal.valueOf(Double.valueOf(0.00)));
        	    }
        	    
        	    if(!StringUtils.isNullOrBlank(huaxianjia)){
        	    	attrValueSupplier.setOtPrice(BigDecimal.valueOf(Double.valueOf(huaxianjiastr)));
        	    }else{
        	    	attrValueSupplier.setOtPrice(BigDecimal.valueOf(Double.valueOf(0.00)));
        	    }
        	    attrValueSupplier.setImage(image);
        	    
        	    if(!StringUtils.isNullOrBlank(tiaoxingma)){
        	    	 attrValueSupplier.setBarCode(tiaoxingma);
    			}else{
    				//13未时间戳 没有读取到图片条形码前面加N标记
    				attrValueSupplier.setBarCode("N_"+String.valueOf(new Date().getTime()));
    			}
        	    String unique=StringUtils.randomString(8,false);
        	    attrValueSupplier.setUnique(unique.toLowerCase());
        	    
        	    if(!StringUtils.isNullOrBlank(weight)){
        	    	weight=weight.toLowerCase();
        	    	weight=weight.substring(0, weight.lastIndexOf("k"));
        	    	attrValueSupplier.setWeight(BigDecimal.valueOf(Double.valueOf(weight)));
        	    }else{
        	    	attrValueSupplier.setWeight(BigDecimal.valueOf(Double.valueOf(0)));
        	    }
        	    attrValueSupplier.setVolume(BigDecimal.valueOf(Double.valueOf(0)));
        	    attrValueSupplier.setBrokerageTwo(BigDecimal.valueOf(Double.valueOf(0)));
        	    attrValueSupplier.setBrokerage(BigDecimal.valueOf(Double.valueOf(0)));
        	    attrValueSupplier.setType(0);
        	    attrValueSupplier.setQuota(0);
        	    attrValueSupplier.setQuotaShow(0);
        	    
        	    List<StoreProductAttrValueSupplier> liststoreProductAttrValue=storeProductAttrValueSupplierService.getList(productidmap);
        	    if(liststoreProductAttrValue==null || liststoreProductAttrValue.isEmpty()){
        	    	storeProductAttrValueSupplierService.save(attrValueSupplier);
        	    }
        	    
        	    
        	    //商品属性详情表
        	    String guigeunicode = testgetUnicode("规格");
        	    String morenunicode = testgetUnicode("默认");
        	    
        	    StoreProductAttrResultSupplier attrResultSupplier=new StoreProductAttrResultSupplier();
        	    attrResultSupplier.setProductId(productId);
        	    attrResultSupplier.setType(0);
        	    
        	    AttrResultSupplierVo resultVo=new AttrResultSupplierVo();
        	    AttrVo attrVo=new AttrVo();
        	    attrVo.setValue(guigeunicode);
        	    attrVo.setDetailValue("");
        	    attrVo.setAttrHidden("");
        	    List <String> detail=new ArrayList<String>();
        	    detail.add(morenunicode);
        	    
        	    
        	    attrVo.setDetail(detail);
        	    List<AttrVo> listAttrVo=new ArrayList<AttrVo>();
        	    listAttrVo.add(attrVo);
        	    resultVo.setAttr(listAttrVo);
        	    
        	    AttrValueVo attrValueVo=new AttrValueVo();
        	    attrValueVo.setPic(attrValueSupplier.getImage());
        	    attrValueVo.setMin_price(String.valueOf(attrValueSupplier.getMinPrice()));
        	    attrValueVo.setOt_price(String.valueOf(attrValueSupplier.getOtPrice()));
        	    attrValueVo.setStock(0);
        	    attrValueVo.setBar_code(attrValueSupplier.getBarCode());
        	    attrValueVo.setVolume(String.valueOf(attrValueSupplier.getVolume()));
        	    attrValueVo.setWeight(String.valueOf(attrValueSupplier.getWeight()));
        	    attrValueVo.setBrokerage("0.00");
        	    attrValueVo.setBrokerage_two("0.00");
        	    attrValueVo.setCost(String.valueOf(attrValueSupplier.getMinPrice()));
        	    attrValueVo.setPrice(String.valueOf(attrValueSupplier.getPrice()));
        	    attrValueVo.setValue1(guigeunicode);
        	    
        	    AttrResultDetailVo vo=new AttrResultDetailVo();
        	    vo.set规格(morenunicode);
        	    attrValueVo.setDetail(vo);
        	    
        	    List<AttrValueVo> listAttrValueVo=new ArrayList<AttrValueVo>();
        	    listAttrValueVo.add(attrValueVo);
        	    resultVo.setValue(listAttrValueVo);
        	    String resultjs=JSON.toJSONString(resultVo);
        	    resultjs=resultjs.replaceAll("规格", testgetUnicode("规格"));
        	    resultjs=resultjs.replaceAll("/", "\\\\");
        	    System.out.println(resultjs);
        	    
//        	    System.out.println(resultjs.replaceAll("\"{", "{"));
//        	    System.out.println(resultjs.replaceAll("}\"", "}"));
        	    attrResultSupplier.setResult(resultjs);
        	    attrResultSupplier.setChangeTime(addTime);
        	    
        	    List<StoreProductAttrResultSupplier> listAttrResultSupplier=storeProductAttrResultSupplierService.getList(productidmap);
        	    if(listAttrResultSupplier==null || listAttrResultSupplier.isEmpty()){
        	    	 storeProductAttrResultSupplierService.save(attrResultSupplier);
        	    }
//        	    String result=spbh+" "+pinpai+" "+name+" "+spjg+" "+cszdj+" "+spguige+" "+zhuyaoyuanliao
//        	    		+" "+yingyangchenfen+" "+shiyongduixiang+" "+kelidaxiao+" "+kouweipeifang
//        	    		+" "+baozhiqi+" "+weight+" "+huaxianjia+" "+tiaoxingma+" "+url;
//        	    FileReadHandler.writeStringToFile2("D://pythontest//readresult.txt",result);
            }
            System.out.println("总条数: "+count);
        } catch (Exception e) {
        	e.printStackTrace();
        	throw new Exception("写入异常");
        }
	    
    String result="OK";
	ResponseVo<String> resVo=new ResponseVo<String>();
	resVo.setResult(result);
 	return resVo;
 }*/
 
 
 
 @ApiOperation(value = "更新商品productcode为空内数据")
 @RequestMapping(value = "/productCodenull", method = RequestMethod.GET)
 public ResponseVo<String> productCodenull() throws Exception{
    String result="OK";
	ResponseVo<String> resVo=new ResponseVo<String>();
	Map<String, Object> map=new HashMap<String,Object>();
	List<StoreProductSupplier> list=storeProductSupplierService.getList(map);
	for(int i=0;i<list.size();i++){
		StoreProductSupplier productSupplier=list.get(i);
		Integer id=productSupplier.getId();
		String productCodeStr=productSupplier.getProductCode();
		if(StringUtils.isNullOrBlank(productCodeStr)){
			StoreProductSupplier updateProduct=new StoreProductSupplier();
			updateProduct.setId(id);
			Date d = new Date();
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    		String dateNowStr = sdf.format(d);
			String shuijicode=StringUtils.getRandomCode(6);
			updateProduct.setProductCode("SP_"+dateNowStr+"_"+shuijicode);
			storeProductSupplierService.update(updateProduct);
			System.out.println("当前执行条数"+i);
		}
	}
	resVo.setResult(result);
 	return resVo;
 }
 
 
 @ApiOperation(value = "更新商品图片路径为D盘路径为标准json")
 @RequestMapping(value = "/updateProductImagPath", method = RequestMethod.GET)
 public ResponseVo<String> updateProductImagPath(@RequestParam(value = "factoryId", required = true) Integer factoryId) throws Exception{
    String result="OK";
	ResponseVo<String> resVo=new ResponseVo<String>();
	Map<String, Object> map=new HashMap<String,Object>();
	map.put("factoryId", factoryId);
	List<StoreProductSupplier> list=storeProductSupplierService.getList(map);
	
	for(int i=0;i<list.size();i++){
		
		StoreProductSupplier storeProductSupplier=list.get(i);
		//设置主图
		String image=storeProductSupplier.getImage();
		
		System.out.println("更新图片路径当前更新条数:"+i+" 商品id"+storeProductSupplier.getId());
		
	    if(!image.contains("//")&& !StringUtils.isNullOrBlank(image)){
	    	image = image.replaceAll("\\\\", "//");
	    	
	    	String sliderImage=storeProductSupplier.getSliderImage();
			List<String> lastsliderImage=sortImage(sliderImage);
			String sliderImagejson="";
			if(lastsliderImage!=null && !lastsliderImage.isEmpty()){
				sliderImagejson=lastsliderImage.toString();
			}
			
			
			String detailImg=storeProductSupplier.getDetailImg();
			List<String> lastsdetailImg=sortImage(detailImg);
			
			String detailImjson="";
			if(lastsdetailImg!=null && !lastsdetailImg.isEmpty()){
				detailImjson=lastsdetailImg.toString();
			}
			
			StoreProductSupplier updateProduct=new StoreProductSupplier();
			updateProduct.setId(storeProductSupplier.getId());
			updateProduct.setImage(image);
			updateProduct.setSliderImage(sliderImagejson);
			updateProduct.setDetailImg(detailImjson);
			storeProductSupplierService.update(updateProduct);
	    	
		}
	}
	resVo.setResult(result);
 	return resVo;
 }
 
 
 private List<String> sortImage(String setailImg) {
	 
	    
	    List<String> pathlist=new ArrayList<String>();
		setailImg=setailImg.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "");
		if(!StringUtils.isNullOrBlank(setailImg)){
			String detailImageArray[]=setailImg.split(",");
			
			List<Integer> listNum=new ArrayList<Integer>();
			String first=detailImageArray[0];
			first=first.substring(0, first.lastIndexOf("_")+1);
			for(int i=0;i<detailImageArray.length;i++){
				String imageStr=detailImageArray[i].trim();
				String name=imageStr.substring(imageStr.lastIndexOf("\\")+1);
				String arrayname[]=name.split("_");
				String namejpg=arrayname[1];
				String num=namejpg.substring(0, namejpg.indexOf("."));
				listNum.add(Integer.valueOf(num));
			}
			Collections.sort(listNum);
			StringBuffer sb=new StringBuffer();
			for(int i=0;i<listNum.size();i++){
				String lastname=first+listNum.get(i)+".jpg";
				lastname = lastname.replaceAll("\\\\", "//");
				sb.append("\""+lastname+"\""+",");
			}
			String lasturl=sb.toString();
			pathlist.add(lasturl.substring(0, lasturl.lastIndexOf(",")));
			
		}
		
		return pathlist;
	}
 
 
 public static String testgetUnicode(String str){
		String result = "";
		char[] c = str.toCharArray();
		for(char tmp:c){	
			if(tmp > 255){  
				result += "/"+"u" + Integer.toHexString(tmp);  
		          
		    }else  
				result += tmp;
		}
		return result;
	}
 
 
 @ApiOperation(value = "使用轮播图第二章更新主图")
 @RequestMapping(value = "/updateProductImag", method = RequestMethod.GET)
 public ResponseVo<String> updateProductImag(@RequestParam(value = "factoryId", required = true) Integer factoryId) throws Exception{
    String result="OK";
	ResponseVo<String> resVo=new ResponseVo<String>();
	Map<String, Object> map=new HashMap<String,Object>();
	map.put("factoryId", factoryId);
	List<StoreProductSupplier> list=storeProductSupplierService.getList(map);
	
	for(int i=0;i<list.size();i++){
		StoreProductSupplier storeProductSupplier=list.get(i);
		//设置主图
		Integer id=storeProductSupplier.getId();
		logger.info("更新图片当前更新条数:"+i+" 商品id"+id);
		String sliderImage=storeProductSupplier.getSliderImage();
		String image=storeProductSupplier.getImage();
		
	    /*if(!StringUtils.isNullOrBlank(sliderImage)){
	    	sliderImage=sliderImage.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "");
	    	String img=null;
	    	
	    	if(!StringUtils.isNullOrBlank(sliderImage)){
	    		String arrayImsge[]=sliderImage.split(",");
	    		if(arrayImsge!=null && arrayImsge.length>0){
	    			if(arrayImsge.length>1){
	    				img=arrayImsge[1];
	    			}else{
	    				img=arrayImsge[0];
	    			}
	    		}
	    	}*/
	    	if(!StringUtils.isNullOrBlank(image)){
	    		StoreProductSupplier updateProduct=new StoreProductSupplier();
				updateProduct.setId(storeProductSupplier.getId());
				image=image.trim();
				image=image.replaceAll("\\\\","");
				System.out.println(image);
				updateProduct.setImage(image);
				storeProductSupplierService.update(updateProduct);
	    		
	    	}
	    	
		}
	resVo.setResult(result);
 	return resVo;
 }
 
 

}
